package com.unbox.common.annotation;

import com.unbox.common.annotation.entity.AnnotionEnitty;
import com.unbox.common.annotation.log.UnboxAnnotationLog;
import com.unbox.common.annotation.log.UnboxDefaulttLog;
import com.unbox.common.annotation.scan.UnboxDefaultAnnotationScan;
import com.unbox.common.annotation.scan.UnBoxAnnotationScan;
import com.unbox.common.annotation.validation.UnboxDefaultValidation;
import com.unbox.common.annotation.validation.UnboxValidation;
import com.unbox.common.annotation.validation.ValidationMaps;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import javax.annotation.PostConstruct;

@Data
public class AnnotationAbstractFactory {

    @Autowired(required = false)
    UnBoxAnnotationScan unBoxAnnotationScan;

    @Autowired(required = false)
    UnboxValidation unboxValidation;

    @Autowired(required = false)
    UnboxAnnotationLog unboxAnnotationLog;

    @PostConstruct
    public void init() {
        // 如果没有注入 实例化框架自身默认实现
        if (unBoxAnnotationScan == null) {
            unBoxAnnotationScan = new UnboxDefaultAnnotationScan();
        }
        if (unboxValidation == null) {
            UnboxDefaultValidation unboxValidation = new UnboxDefaultValidation();
            unboxValidation.setValidationMaps(new ValidationMaps().init());
            this.unboxValidation = unboxValidation;
        }
        if (unboxAnnotationLog == null) {
            unboxAnnotationLog = new UnboxDefaulttLog();
        }
    }

    @Bean
    public ValidationMaps validationMaps(){
        return new ValidationMaps().init();
    }

    /**
     * 自定义注解验证
     * @param obj
     * @param method
     * @param types
     * @throws NoSuchMethodException
     */
    public void validated(Object obj, String method, Object[] types) throws Exception {
        AnnotionEnitty annotionEnitty = unBoxAnnotationScan.scanMethodAnnotation(obj, method, types);
        String msg = unboxValidation.check(annotionEnitty);
        if (msg != null){
            throw new Exception(msg);
        }
    }
}
